<?php

namespace App\Models;


use App\Helpers\commonFuc;
use Illuminate\Support\Facades\DB;

class Config
{
    /**获取系统配置
     * @param $keyname 键名称
     * @param array $defvalue  默认值，如果没有自动插入一条
     * @return array|mixed
     */
    static function getValue($keyname,$defvalue=[]){
        $configdb = DB::table('config')->where('keyname',$keyname)->get();

        if(count($configdb)==0){
            self::setValue($keyname, $defvalue);
            return $defvalue;
        }else if(count($configdb)==1){
            $defvalue=$configdb[0]->value;
            $defvaluejson = json_decode($defvalue, true);
            if($defvaluejson){
                return $defvaluejson;
            }
            return $defvalue;
        }
        $retrues = [];
        foreach ($configdb as $configdb1){
            $defvaluejson = json_decode($configdb1->value, true);
            if($defvaluejson){
                $retrues[]=$defvaluejson;
            }else{
                $retrues[]=$configdb1->value;
            }

        }
        return $retrues;

    }

    /**设置配置
     * @param $keyname
     * @param $defvalue
     * @param string $title
     * @return false|mixed|string
     */
    static function setValue($keyname,$defvalue,$title=''){
        if(is_array($defvalue)){
            $defvalue=json_encode($defvalue,JSON_UNESCAPED_UNICODE);
        }else if(is_object($defvalue)){
            $defvalue = commonFuc::object_to_array($defvalue);
            $defvalue=json_encode($defvalue,JSON_UNESCAPED_UNICODE);
        }
        $configdb = DB::table('config')->where('keyname',$keyname)->get();
        $updatad = [
            'keyname' => $keyname
            , 'value' => $defvalue
        ];
        if($title!=''){
            $updatad['title'] = $title;
        }
        if(count($configdb)>0){
            DB::table('config')->where('keyname',$keyname)->update($updatad);
        }else{
            DB::table('config')->insert($updatad);
        }

        return $defvalue;
    }
}
